//
//  ZYHomeVC.m
//  ZYOils
//
//  Created by WANGGNIT on 2019/7/18.
//  Copyright © 2019 WANGGNIT. All rights reserved.
//

#import "ZYHomeVC.h"

#import "ZYOilsPriceViewController.h"
#import "ZYReportViewController.h"
#import "ZYPaymentRecordsViewController.h"
#import "ZYCodeViewController.h"
#import "ZYBillListViewController.h"
#import "ZYMyStoreViewController.h"
#import "ZYSetTableViewController.h"
#import "ZYPersonManagerViewController.h"

#import "ZYHomeBillTableViewCell.h"
#import "ZYHomeFuncCollectionViewCell.h"
#import "ZYOils-Swift.h"
#import "ZYTodayBillInfoModel.h"
#import "ZYHomePopView.h"

#import "ZYOilsInfoModel.h"

@interface ZYHomeVC () <UICollectionViewDelegate, UICollectionViewDataSource, UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIView *funcContentView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *funcHeightLayout;


@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) UICollectionView *collectionView;

@property(nonatomic, strong) UIView *layerView;

@property (nonatomic, strong) NSArray *funcLists;

@property (nonatomic, strong) ZYTodayBillInfoModel *infoModel;

@property (weak, nonatomic) IBOutlet UILabel *totalMoneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *decLabel;

@property (nonatomic, strong) ZYHomePopView *popView;

@property (nonatomic, strong) NSMutableArray *oilsLists;

@end

@implementation ZYHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    
    // self.view.ly_emptyView = [self emptyView:XREmptyViewStateNoNetwork];
    // [self.view ly_showEmptyView];
    
    [self customUI];
    [self configData];
}

- (void)requestRefreshData {
    NSLog(@"重新请求数据");
    [self.view ly_hideEmptyView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self configData];
}

#pragma mark - UI

/// 初始化UI
- (void)customUI {
    
    if ([ZYUserInfoModel isManager]) {
        self.funcLists = @[@{@"img": @"home_home_gray", @"name": @"我的门店"},
        @{@"img": @"person_home_gray", @"name": @"人员管理"},
        @{@"img": @"chart_home_gray", @"name": @"经营报表"},
        @{@"img": @"home_oils_gray", @"name": @"油价"},
        @{@"img": @"home_list_gray", @"name": @"账单列表"},
        @{@"img": @"set_home_gray", @"name": @"设置"}];
    } else {
        self.funcLists = @[@{@"img": @"home_list_gray", @"name": @"账单列表"},
        @{@"img": @"set_home_gray", @"name": @"设置"}];
    }
    
    [self.funcContentView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.funcContentView);
    }];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZYHomeBillTableViewCell" bundle:nil] forCellReuseIdentifier:@"ZYHomeBillTableViewCell"];    
}

- (void)configData {
    
    NSDictionary *dict = @{@"managerId": STR(ZYUserInfoModel.sharedInfoModel.userModel.managerId),
                           @"userId": STR(ZYUserInfoModel.sharedInfoModel.userModel.userId),
                           @"page": @"1",
                           @"size": @"2"};
    if (self.infoModel.billMoneyInfo.total == nil) {
        [ZYHud showLoadingText:@""];
    }
    [[DataManager manager] postTodayBillInfoParam:dict block:^(XRCommonModel *model, NSError *error) {
        [ZYHud hideHud];
        if (model.isSuccess) {
            self.infoModel = [ZYTodayBillInfoModel mj_objectWithKeyValues:model.data];
            self.decLabel.text = [NSString stringWithFormat:@"今日收款%@笔,总计", self.infoModel.billMoneyInfo.total];
            self.totalMoneyLabel.text = self.infoModel.billMoneyInfo.toalMoney;
            [self.tableView reloadData];
        } else {
            if (![LBLimitInput isEmpty:model.error]) {
                [ZYHud showErrorText:model.error];
            }
        }
    }];
}

- (void)getOilList {
    /// 获取油品
       NSDictionary *oilDict = @{@"companyId": STR(ZYUserInfoModel.sharedInfoModel.userModel.companyId),
                                 @"page": @"1",
                                 @"size": @"100"};
       [ZYHud showLoadingText:@""];
       [[DataManager manager] postFindOilParam:oilDict block:^(XRCommonModel *model, NSError *error) {
           [ZYHud hideHud];
           if (model.isSuccess) {
               self.oilsLists = [ZYOilsInfoModel mj_objectArrayWithKeyValuesArray:model.data];
               [self.navigationController.view addSubview:self.popView];
               self.popView.list = self.oilsLists;
               [self.popView mas_makeConstraints:^(MASConstraintMaker *make) {
                   make.edges.mas_equalTo(self.navigationController.view);
               }];
           } else {
               if (![LBLimitInput isEmpty:model.error]) {
                   [ZYHud showErrorText:model.error];
               }
           }
       }];
}

#pragma mark - Action
- (IBAction)codeBtnClick:(id)sender {

    if (self.oilsLists.count == 0) {
        [self getOilList];
    } else {
        self.popView.list = self.oilsLists;
        [self.navigationController.view addSubview:self.popView];
        [self.popView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.navigationController.view);
        }];
    }
    
    @weakify(self)
    [self.popView.subject subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        self.popView = nil;
        ZYCodeViewController *controller = [ZYCodeViewController new];
        controller.model = dict[@"model"];
        controller.price = dict[@"price"];
        [self.navigationController pushViewController:controller animated:YES];
    }];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoModel.billInfoResponse.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYHomeBillTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZYHomeBillTableViewCell"];
    cell.model = self.infoModel.billInfoResponse[indexPath.row];
    return cell;
}

-  (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    UILabel *titleLabel = [UILabel new];
    [titleLabel setText:@"收款记录"];
    [titleLabel setTextColor:[UIColor whiteColor]];
    [titleLabel setFont:[UIFont systemFontOfSize:20]];
    [headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(13);
        make.centerY.mas_equalTo(headerView);
    }];
    
    UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [headerView addSubview:moreBtn];
    [moreBtn setTitle:@"查看更多" forState:UIControlStateNormal];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-13);
        make.bottom.mas_equalTo(titleLabel.mas_bottom);
    }];
    
    [[moreBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl *sender) {
        ZYPaymentRecordsViewController *controller = [ZYPaymentRecordsViewController new];
        [self.navigationController pushViewController:controller animated:YES];
    }];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}


#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.funcLists.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZYHomeFuncCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZYHomeFuncCollectionViewCell" forIndexPath:indexPath];
    NSDictionary *dict = self.funcLists[indexPath.row];
    UIImage *iconImage = [UIImage imageNamed:[dict objectForKey:@"img"]];
    cell.iconImageView.image = [iconImage changeColorWithColor:[UIColor whiteColor]];
    cell.titleLabel.text = [dict objectForKey:@"name"];
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (![ZYUserInfoModel isManager]) {
        /// 店员
        if (indexPath.row == 0) {
            /// 账单列表
            ZYBillListViewController *controller = [ZYBillListViewController new];
            [self.navigationController pushViewController:controller animated:YES];
        } else {
            [self.navigationController pushViewController:[ZYSetTableViewController new] animated:YES];
        }
        return;
    }
    if (indexPath.row == 0) {
        /// 店长
        /// 我的门店
        ZYMyStoreViewController *controller = [[UIStoryboard storyboardWithName:@"ZYMyStoreViewController" bundle:nil] instantiateInitialViewController];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if (indexPath.row == 1) {
        /// 人员管理
        ZYPersonManagerViewController *controller = [ZYPersonManagerViewController new];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if (indexPath.row == 2) {
        /// 经营报表
        ZYReportViewController *controller = [ZYReportViewController new];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if (indexPath.row == 3) {
        /// 油价
        ZYOilsPriceViewController *controller = [ZYOilsPriceViewController new];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if (indexPath.row == 4) {
        /// 账单列表
        ZYBillListViewController *controller = [ZYBillListViewController new];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else if (indexPath.row == 5) {
        /// 设置
        [self.navigationController pushViewController:[ZYSetTableViewController new] animated:YES];
    }
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width;
        if ([ZYUserInfoModel isManager]) {
            width = (SCREEN_WIDTH - 13) / 2.5;
        } else {
            width = (SCREEN_WIDTH - 13) / 2;
        }
        
        layout.itemSize = CGSizeMake(width, 140);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.sectionInset = UIEdgeInsetsMake(0, -5, 0, -5);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = BACKGROUNDCOLOR;
//        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerNib:[UINib nibWithNibName:@"ZYHomeFuncCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ZYHomeFuncCollectionViewCell"];
    }
    return _collectionView;
}


- (ZYTodayBillInfoModel *)infoModel {
    if (!_infoModel) {
        _infoModel = [[ZYTodayBillInfoModel alloc] init];
    }
    return _infoModel;
}

- (ZYHomePopView *)popView {
    if (_popView == nil) {
        _popView = [[[NSBundle mainBundle] loadNibNamed:@"ZYHomePopView" owner:nil options:nil] lastObject];
    }
    
    return _popView;
}

- (NSMutableArray *)oilsLists {
    if (!_oilsLists) {
        _oilsLists = [[NSMutableArray alloc] init];
    }
    return _oilsLists;
}


@end
